package com.red.wine.ui;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.red.wine.R;
import com.red.wine.adapter.ImageAdapter;
import com.red.wine.adapter.TasteAdapter;
import com.red.wine.model.DataInfo;
import com.red.wine.model.Headers;
import com.red.wine.model.ReturnInfo;
import com.red.wine.model.TasteInfo;
import com.red.wine.model.TasteRequest;
import com.red.wine.model.TasteReturnData;
import com.red.wine.util.IntentUtil;
import com.red.wine.util.PrefsUtils;
import com.red.wine.util.StringUtil;
import com.red.wine.webservice.ServiceAsynTask;
import com.red.wine.webservice.ServiceHelper;
import com.red.wine.webservice.ServiceHost;
import com.red.wine.widget.GalleryFlow;
import com.red.wine.widget.ImageAdapters;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
/**
 * 推荐
 * @author yanghaiyang
 * 2013-10-20上午2:25:39
 * {@link describe}
 */
public class PerodeActivity extends BaseActivity{
	private Context context;
	View[] views = new View[3];
	GalleryFlow galleryFlow;
	DisplayMetrics displayMetrics;
	TextView perde;
	ListView listView;
	ImageView back;
	boolean isback = true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wangqi);
		context = this;

		displayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		getData(3);
		galleryFlow = (GalleryFlow) findViewById(R.id.Gallery01);
		perde = (TextView) findViewById(R.id.taset_top_btnss);
		listView = (ListView) findViewById(R.id.taste_listview_for_listsssss);
		back = (ImageView) findViewById(R.id.top_back_btns_5);
		listView.setCacheColorHint(Color.TRANSPARENT);
		perde.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
//				if(galleryFlow.getChildCount() > 0){
//					galleryFlow.rem
//				}
				galleryFlow.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				getData(15);
				isback = false;
			}
		});

		back.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				finish();
//				galleryFlow.setVisibility(View.VISIBLE);
//				if(listView.getChildCount() > 0){
//					listView.removeAllViews();
//				}
//				listView.setVisibility(View.GONE);
//				getData(3);
//				isback = true;
			}
		});
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				showLoading();
				Bundle bundle = new Bundle();
				bundle.putSerializable("info", data);
				IntentUtil.redirectToNext(context, TasteSecondActivity.class, bundle);
				hideLoading();
			}
		});
	}
	
	private void getData(final int num) {
		showLoading();
		new ServiceAsynTask<ReturnInfo>() {

			@Override
			protected ReturnInfo callService() throws IOException,
					JsonParseException, AssertionError {
				TasteRequest taste = new TasteRequest();
				Headers header = new Headers();
				header.setUa("ANDROID_HY/2.0.1.0 (customerid=gypsii, variant=gypsii)");

				DataInfo data = new DataInfo();
				data.setNum(num);
				data.setSince_id(0);
				data.setCat(3);
				Log.e("TAG", PrefsUtils.getIndex());
				// data.setCat(1);
				taste.cmd = "event_lists";
				taste.headers = header;
				taste.data = data;
				taste.sid = "";

				String up = new Gson().toJson(taste);
				String send = StringUtil.unicodeToUtf8("json=" + up);
				String urlstr = ServiceHost.getTasteURL();

				return ServiceHelper.getInstance().postData(urlstr, send,
						ReturnInfo.class);
			}

			@Override
			protected void runWithResult(ReturnInfo result) throws Exception {
				
				if (result != null) {
					bindData(result, num);
					Log.e("TAG", "isnotnull");
				} else {
					Log.e("TAG", "is null");
				}
				
			}

			@Override
			protected void runWithError(ReturnInfo result, int iErrorCode)
					throws Exception {
				Log.e("TAG", "异常" + iErrorCode);
				hideLoading();
				finish();
			}
		}.execute();
	}
	TasteReturnData data;
	private List<TasteInfo> listData;
	List<Bitmap> bitmaps = new ArrayList<Bitmap>();
	private TasteAdapter listadapter;
	protected void bindData(ReturnInfo returninfo, int num) {
		if (returninfo != null && returninfo.getData() != null) {
			data = returninfo.getData();
		}
		if (data != null && data.getItems() != null) {
			listData = data.getItems();
		}
		
		 if(listData != null && listData.size() > 0){
			 if(num == 3){
				  for(int i=0; i<listData.size(); i++){
			        	View view = LayoutInflater.from(context).inflate(R.layout.wangqi_item_layout, null);
			        	TextView title1 = (TextView) view.findViewById(R.id.wangqi_title_1);
			        	TextView title2 = (TextView) view.findViewById(R.id.wangqi_title_2);
			        	ImageView icon = (ImageView) view.findViewById(R.id.wangqi_item_img_s);
			        	TextView title3 = (TextView) view.findViewById(R.id.wangqi_title_3);
			        	TextView title4 = (TextView) view.findViewById(R.id.wangqi_title_4);
			        	TextView title5 = (TextView) view.findViewById(R.id.wangqi_title_5);
			        	TextView title6 = (TextView) view.findViewById(R.id.wangqi_title_6);
			        	TextView title7 = (TextView) view.findViewById(R.id.wangqi_title_7);
			        	TextView title8 = (TextView) view.findViewById(R.id.wangqi_title_8);
			        	title1.setText("");
			        	title2.setText(listData.get(i).getTitle() + "");
			        	if(!StringUtil.isEmptyOrNull(listData.get(i).getThumbnail_64().get(0))){
			        		icon.setImageBitmap(downImg(listData.get(i).getThumbnail_64().get(0)));
			        	}
			        	title3.setText("酒庄：" + listData.get(i).getTitle());
			        	title4.setText("产地：" + listData.get(i).getWine_origin());
			        	title5.setText("葡萄酒品种：" + listData.get(i).getWine_type());
			        	title6.setText("酒精度： " + listData.get(i).getWin_degree());
			        	title7.setText("类别：" + listData.get(i).getWine_type());
			        	title8.setText("\r\r" + listData.get(i).getContent());
			        	views[i] = view;
			        }
		  		ImageAdapters adapter = new ImageAdapters(this, views, displayMetrics.widthPixels, displayMetrics.heightPixels);
				adapter.createReflectedImages();
				galleryFlow.setAdapter(adapter);
			} else if (num == 15) {
				listadapter = new TasteAdapter(context, listData);
				listView.setAdapter(listadapter);
			}
		}
		hideLoading();
	}
	
	private Bitmap downImg(String imgurl) {
		// 启动一个后台线程
		// 这里下载数据
		Bitmap downBItmap = null;
		try {
			URL url = new URL(imgurl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			downBItmap = BitmapFactory.decodeStream(is);
			is.close();
			conn.disconnect();
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return downBItmap;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(isback){
			IntentUtil.redirectToNext(context, MainActivity.class);
			finish();
		}else{
			galleryFlow.setVisibility(View.VISIBLE);
			if(listView.getChildCount() > 0){
				listView.removeAllViews();
			}
			listView.setVisibility(View.GONE);
			getData(3);
			isback = true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
